package ch.kerbtier.malurus.updaters;

import java.util.HashMap;
import java.util.Map;

import ch.kerbtier.malurus.Component;
import ch.kerbtier.malurus.RequestContext;
import ch.kerbtier.malurus.UpdateProvider;
import ch.kerbtier.malurus.Updater;

public class JavaUpdateProvider implements UpdateProvider {
	private Map<String, Updater> updaters = new HashMap<String, Updater>();

	protected void addUpdater(String component, String realisation, Class updater) {
		updaters.put(component + (realisation == null ? "" : "->" + realisation), new JavaUpdater(updater));
	}

	public Updater getUpdater(String component, String realisation) {
		return updaters.get(component + (realisation == null ? "" : "->" + realisation));
	}

	public void update(Component component, RequestContext requestContext) {
	}

	class JavaUpdater implements Updater {
		private Class javaComponentUpdater;

		public JavaUpdater(Class javaComponentUpdater) {
			this.javaComponentUpdater = javaComponentUpdater;
		}

		public void update(Component component, RequestContext requestContext) {
			if (component.isVisible()) {
				try {
					JavaComponentUpdater updater = (JavaComponentUpdater) javaComponentUpdater.newInstance();
					updater.setContext(requestContext);
					updater.setSubject(component);
					updater.update();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
